package org.framework.lazy.cloud.network.heartbeat.protocol.filter;

import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.socksx.v5.Socks5CommandRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5InitialRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5ServerEncoder;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.HandleChannelTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.factory.EventLoopGroupFactory;
import org.framework.lazy.cloud.network.heartbeat.common.filter.DebugChannelInitializer;
import org.framework.lazy.cloud.network.heartbeat.protocol.handler.NettySocks5CommandRequestHandler;
import org.framework.lazy.cloud.network.heartbeat.protocol.handler.NettySocks5InitialRequestHandler;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * description
 *
 * @author 吴佳伟
 * @date 2023/09/13 10:26
 */
@Component
public class NettyTcpProxyFilter extends DebugChannelInitializer<SocketChannel> {
    private final List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedList;

    public NettyTcpProxyFilter(List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedList) {
        this.handleChannelTypeAdvancedList = handleChannelTypeAdvancedList;
    }

    @Override
    protected void initChannel0(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 类型处理器适配器
        ChannelTypeAdapter channelTypeAdapter = new ChannelTypeAdapter(handleChannelTypeAdvancedList);


        //socks5响应最后一个encode
        pipeline.addLast(Socks5ServerEncoder.DEFAULT);
        // 初始化连接
        pipeline.addLast(new Socks5InitialRequestDecoder());
        pipeline.addLast(new NettySocks5InitialRequestHandler());


        // 认证
        // ch.pipeline().addLast(new Socks5PasswordAuthRequestDecoder());
        // ch.pipeline().addLast(new Socks5PasswordAuthRequestInboundHandler());

        EventLoopGroup clientWorkGroup = EventLoopGroupFactory.createClientWorkGroup();

        // 连接请求
        pipeline.addLast(new Socks5CommandRequestDecoder());
        pipeline.addLast(new NettySocks5CommandRequestHandler(channelTypeAdapter));



    }
}